package controller

import (
	"context"
	"fmt"
	"gitee.com/worklz/dtm-tcc-demo/common/log"
	"gitee.com/worklz/dtm-tcc-demo/common/response"
	"gitee.com/worklz/dtm-tcc-demo/gateway/app/dto"
	"gitee.com/worklz/dtm-tcc-demo/gateway/pkg/global"
	orderpb "gitee.com/worklz/dtm-tcc-demo/server-order/proto/order"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

type OrderController struct {
	Controller
}

func (c *OrderController) Detail(ctx *gin.Context) {
	// 数据获取校验
	req := dto.OrderReq{}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		response.Fail(ctx, err.Error())
		return
	}
	// 调用 grpc 订单服务获取订单数据
	client, conn, err := GetGrpcOrderServiceClient()
	defer func() {
		if conn == nil {
			return
		}
		if closeErr := conn.Close(); closeErr != nil {
			log.Error("关闭 grpc 订单服务连接失败！", closeErr)
		}
	}()
	if err != nil {
		response.Fail(ctx, err.Error())
	}
	orderReq := &orderpb.GetOrderRequest{
		OrderId: req.Id,
	}
	orderRes, orderErr := client.GetOrder(context.Background(), orderReq)
	if orderErr != nil {
		response.Fail(ctx, fmt.Sprintf("获取订单数据失败: %v", orderErr))
		return
	}
	resData := dto.OrderResData{
		OrderId:   orderRes.OrderId,
		UserId:    orderRes.UserId,
		ProductId: orderRes.ProductId,
		Quantity:  orderRes.Quantity,
		Amount:    orderRes.Amount,
		Status:    orderRes.Status,
	}
	response.Success(ctx, resData)
}

// GetGrpcOrderServiceClient 获取 grpc 订单服务客户端
func GetGrpcOrderServiceClient() (client orderpb.OrderServiceClient, conn *grpc.ClientConn, err error) {
	conn, err = grpc.NewClient(global.Config.Grpc.ServerAddr.Order,
		grpc.WithTransportCredentials(insecure.NewCredentials()), // 开发环境使用不安全凭证
		// 可添加其他选项，如超时设置
		// grpc.WithTimeout(5*time.Second),
	)
	if err != nil {
		return
	}
	client = orderpb.NewOrderServiceClient(conn)
	return
}
